<?php

namespace common\models;

use Yii;
use yii\base\Model;
use Helper;

class Validate extends Model
{
    public $guide = 0;
    public $gid = "";
    public $t = "sms";
    public $code = "";
    public $appkey = "";
    public $codetype = "-1";
    public $email = "";
    public $mobile = "";
    public $country = "CN";

    const SCENARIO_GID = "checkbygid";
    const SCENARIO_EMAIL = "checkbyemail";
    const SCENARIO_MOBILE = "checkbymobile";

    public function rules()
    {
        return [
            ['appkey', 'required', 'on' => [self::SCENARIO_GID, self::SCENARIO_EMAIL, self::SCENARIO_MOBILE], 'message' => Yii::t('code', '1001')],
            ['t', 'required', 'on' => [self::SCENARIO_GID, self::SCENARIO_EMAIL, self::SCENARIO_MOBILE], 'message' => Yii::t('code', '1001')],
            ['code', 'required', 'on' => [self::SCENARIO_GID, self::SCENARIO_EMAIL, self::SCENARIO_MOBILE], 'message' => Yii::t('code', '1026')],
            ['country', 'required', 'on' => [self::SCENARIO_MOBILE], 'message' => Yii::t('code', '1002')],
            ['country', 'checkCountry', 'skipOnError' => false, 'skipOnEmpty' => false, 'on' => [self::SCENARIO_MOBILE]],
            ['mobile', 'required', 'on' => [self::SCENARIO_MOBILE], 'message' => Yii::t('code', '1003')],
            ['mobile', 'checkMobile', 'on' => [self::SCENARIO_MOBILE]],
            ['email', 'required', 'on' => self::SCENARIO_EMAIL, 'message' => Yii::t('code', '1020')],
            ['email', 'checkEmail', 'on' => self::SCENARIO_EMAIL],
            ['gid', 'required', 'on' => [self::SCENARIO_GID], 'message' => Yii::t('code', '1024')],
            ['codetype', 'default', 'value' => -1],
            ['codetype', 'string', 'length' => [1, 25], 'message' => Yii::t('code', '1009')],
            [['guide'], 'integer'],
        ];
    }

    public function checkCountry($attribute, $params)
    {
        $countrys = require(Yii::getAlias('@common/data/country.php'));
        if ((!isset($countrys[$this->country]) || empty($countrys[$this->country]))) {
            $name = array_search($this->country, array_column($countrys, 'code', 'sname'));
            if ($name === false) {
                $this->addError($attribute, Yii::t('code', '1005'));
            }
        }
    }

    public function checkMobile($attribute, $params)
    {
        if ($this->country != "CN" && $this->country != "86") {
            $flag = Helper::isMobile($this->mobile, true);
        } else {
            $flag = Helper::isMobile($this->mobile, false);
        }
        if (!$flag) {
            $this->addError($attribute, Yii::t('code', '1004'));
        }
    }


    public function checkEmail($attribute, $params)
    {
        if ($this->email) {
            if (!Helper::isEmail($this->email)) {
                $this->addError($attribute, Yii::t('code', '1021'));
            }
        }
    }

}

?>